package com.test.daily.leetcode.y2022.m05.day0522.v01;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/5/22 下午 02:33
 * @version: 1.0
 */
public class Solution {
    public static void main(String[] args) {

    }
    public static class Node{
        int value;
        Node left;
        Node right;
        public Node(int value){
            this.value = value;
        }
    }
    public static Node buildByPre(Queue<String> prelist){
        if(prelist == null || prelist.size() == 0){
            return null;
        }
        return byPre(prelist);
    }
    public static Node byPre(Queue<String> prelist){
        String value = prelist.poll();
        if(value == null){
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.left = byPre(prelist);
        head.right = byPre(prelist);
        return head;
    }
    public static Node buildByPost(Queue<String> postList){
        if(postList == null || postList.size() == 0){
            return null;
        }
        Stack<String> stack = new Stack<>();
        while(!postList.isEmpty()){
            stack.push(postList.poll());
        }
        return byPost(stack);
    }
    public static Node byPost(Stack<String> stack){
        String value = stack.pop();
        if(value == null){
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.right = byPost(stack);
        head.left = byPost(stack);
        return head;
    }

    public static Node buildByLevel(Queue<String> levelList){
        if(levelList == null || levelList.size() == 0){
            return null;
        }
        Node head = new Node(Integer.valueOf(levelList.poll()));
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        while(!queue.isEmpty()){
            head = queue.poll();
            head.left = new Node(Integer.valueOf(levelList.poll()));
            head.right = new Node(Integer.valueOf(levelList.poll()));
            if(head.left != null){
                queue.add(head.left);
            }
            if(head.right != null){
                queue.add(head.right);
            }
        }
        return head;
    }
}
